package com.seguridad.ws.handler.model;

import java.util.ArrayList;
import java.util.List;

import javax.xml.crypto.dsig.XMLSignature;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class HMACSignatureBuilder {

	public static HMACSignature build(Element doc){
		HMACSignature signature = null;
		
		// Busca y crea las referencias
		NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Reference");
		List<SignatureReference> references = new ArrayList<SignatureReference>();
		for (int i = 0; i < nl.getLength(); i++) {
			Node node = nl.item(i);
			String uri = node.getAttributes().getNamedItem("URI").getNodeValue();
			String digestedValue = "";
			
			NodeList childs = node.getChildNodes();
			for (int j = 0; j < childs.getLength(); j++) {
				Node child = childs.item(j);
				child.getLocalName();
				if("DigestValue".equalsIgnoreCase(child.getLocalName())){
					digestedValue = child.getTextContent();
				}
			}
			
			SignatureReference reference = new SignatureReference(uri, digestedValue);
			references.add(reference);
		}
		
		// Busca el valor de la firma
		NodeList nl2 = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "SignatureValue");
		Node node = nl2.item(0);
		String signatureValue = node.getTextContent();
		
		// Busca en caso de existir el valor a truncar del hmac
		Integer hmacOutputBits = 160;
		NodeList nl3 = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "HMACOutputLength");
		if(nl3.getLength() > 0){
			Integer hmacParameter = Integer.parseInt(nl3.item(0).getTextContent());
			if(hmacParameter < 160 && hmacParameter >= 0){
				hmacOutputBits = hmacParameter;
			}
		}
		
		// Crea la firma
		signature = new HMACSignature(references, signatureValue, hmacOutputBits);
		
		return signature;
	}
}
